<template>
  <div>
    <CategorySelector :disabled="!attrListOrAdd"></CategorySelector>
    <el-card shadow="always" style="margin-top: 20px">
      <!-- 平台属性数据列表模块 -->
      <div v-if="attrListOrAdd">
        <el-button
          type="primary"
          icon="ele-Plus"
          @click="addAttr()"
          :disabled="!category3Id"
          >添加属性</el-button
        >
        <el-table :data="attrListInfo" border stripe>
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column label="属性名称" prop="attrName" width="150">
          </el-table-column>
          <el-table-column label="属性值名称列表">
            <template #="{ row }">
              <el-tag type="success" v-for="attrValue in row.attrValueList">{{
                attrValue.valueName
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #="{ row }">
              <el-button
                type="warning"
                icon="ele-Edit"
                @click="addAttr(row)"
              ></el-button>
              <el-popconfirm
                title="你确定要删除吗？"
                @confirm="confirmDeleteAttrHandler(row.id)"
              >
                <template #reference>
                  <el-button type="danger" icon="ele-Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加属性模块 -->
      <div v-else>
        <el-form inline>
          <!-- 不写inline的话input输入框会占整行 -->
          <el-form-item label="属性名">
            <!-- 
              在 Vue 的模板中不能使用 ? 这个可选链操作符
              使用 !（告诉ts，!之前的数据类型排除null|undefined等情况）
             -->
            <el-input
              placeholder="输入属性名"
              v-model="formData!.attrName"
              @keydown.enter="enterAttrNameHandler"
              @blur="enterAttrNameHandler"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :disabled="!formData!.attrName"
              @click="addAttrVal"
              >添加属性值</el-button
            >
            <el-button @click="attrListOrAdd = true">取消</el-button>
          </el-form-item>

          <el-form>
            <el-table
              style="margin: 10px 0"
              border
              stripe
              :data="formData!.attrValueList"
            >
              <el-table-column
                label="序号"
                type="index"
                width="100"
              ></el-table-column>
              <el-table-column label="属性值名称">
                <template #="{ row }">
                  <span
                    v-if="!row.isEdit"
                    @dblclick="changeInputStatusHandler(row)"
                    >{{ row.valueName }}</span
                  >
                  <el-input
                    v-else
                    ref="attrValueInputRef"
                    v-model="inputAttrValue"
                    @blur="enterNewAttrValueHandler(row, $event)"
                    @keydown.enter="enterNewAttrValueHandler(row, $event)"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #="{ row }">
                  <el-button
                    type="danger"
                    icon="ele-Delete"
                    @click="deleteAttrValuehandler(row)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button
              type="primary"
              :disabled="!(formData!.attrName && formData!.attrValueList.length > 0)"
              @click="saveAttrHandler"
              >保存</el-button
            >
            <el-button>取消</el-button>
          </el-form>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch, nextTick } from "vue";
export default defineComponent({
  name: "ProductAttrList",
});
</script>
<script lang="ts" setup>
import _ from "lodash";
import CategorySelector from "@/components/CategorySelector/index.vue";
import type { attrInfo, typeSaveAttrRef, ReqSaveAttrValue } from "@/api/attr";
import useCategorySelector from "@/hooks/categorySelector";
import { ElInput, ElMessage } from "element-plus";
import { reqAttrInfoList, reqSaveAttrInfo, reqDeleteAttr } from "@/api/attr";

const { category1Id, category2Id, category3Id } = useCategorySelector();
const attrListInfo = ref<attrInfo[]>([]);

//数据1:记录当前是平台属性数据列表模块(true)/添加属性模块(false)
const attrListOrAdd = ref(true);
//数据2：保存平台属性请求参数
const formData = ref<typeSaveAttrRef | null>();

async function getAttrs() {
  if (category3Id.value !== "") {
    const res = await reqAttrInfoList(
      Number(category1Id.value),
      Number(category2Id.value),
      Number(category3Id.value)
    );
    console.log("平台属性列表", res);
    attrListInfo.value = res;
  }
}

watch(category3Id, getAttrs,{
  immediate:true
});
//数据3:绑定收集用户在属性值列表输入框中输入的数据
const inputAttrValue = ref("");
//数据4:获取属性值的实例对象
const attrValueInputRef = ref<typeof ElInput | null>(null);
//数据5:存储所有的属性列表数据
const attrs = ref<attrInfo[]>([]);

//事件1：添加属性按钮点击事件
const addAttr = (row?: attrInfo) => {
  attrListOrAdd.value = false;
  //初始化平台属性请求参数
  if (row) {
    // 编辑的初始化
    // 使用深拷贝
    formData.value = _.cloneDeep(row);
  } else {
    // 添加初始化
    formData.value = {
      categoryId: Number(category3Id.value),
      categoryLevel: 3,
      attrName: "",
      attrValueList: [],
    };
  }
};
//事件2:添加属性值按钮 点击事件
const addAttrVal = () => {
  formData.value?.attrValueList.push({
    valueName: "",
    isEdit: true,
  });
  nextTick(() => {
    attrValueInputRef.value?.focus();
  });
};
//事件3:点击删除按钮删除指定的属性值
function deleteAttrValuehandler(row: ReqSaveAttrValue) {
  if (formData.value) {
    formData.value.attrValueList = formData.value.attrValueList.filter(
      (item) => item != row
    );
  }
}
//事件4:点击span进入编辑状态
function changeInputStatusHandler(row: ReqSaveAttrValue) {
  // 把当前row的状态设置为true
  row.isEdit = true;
  // 给 inputAttrValue 设置值，值就是当前row.valueName
  inputAttrValue.value = row.valueName;
  // 给当前的input设置焦点
  nextTick(() => {
    attrValueInputRef.value?.focus();
  });
}
//事件5:确认输入框的值
function enterNewAttrValueHandler(row: ReqSaveAttrValue, e: Event) {
  // 判断当前值是否为空
  const newValue = inputAttrValue.value.trim();
  // 获取当前用户输入的内容
  // console.log(row.isEdit, inputAttrValue.value, e);
  // 如果按下回车，会触发两次事件：keydown，blur，原因：keydown添加完数据以后，会把状态设置为false，导致input不被渲染，从而失去焦点了，触发blur
  // 解决
  // 解决办法一：
  // if (e.type == "keydown") {
  //   row.isEdit = false;
  //   return;
  // }
  // 解决办法二：
  if (!row.isEdit && newValue == "") {
    return;
  }
  if (newValue === "") {
    // 如果用户没有输入任何内容，则表示放弃这次添加
    // 也就是从 formData.value.attrValueList 删除 row
    // console.log(row);
    if (formData.value) {
      formData.value.attrValueList = formData.value.attrValueList.filter(
        (item) => item != row
      );
      inputAttrValue.value = "";
    }
  } else {
    // 判断当前要添加的值是否在数组中已经存在
    // 需要在查找的过程中排除自身的比较（item == row）
    const isExists = formData.value?.attrValueList.find(
      (item) => item.valueName == newValue && item != row
    );

    // console.log(isExists);
    if (isExists) {
      // 表示当前数据已经存在了，不允许添加
      inputAttrValue.value = "";
      ElMessage.error("已经存在该值");
      nextTick(() => {
        attrValueInputRef.value?.focus();
      });
    } else {
      // 如果用户输入了内容，则把这个输入内容添加到当前row的valueName属性
      row.valueName = newValue;
      // 把编辑状态修改为显示的状态
      // inputValueNameStatus.value = false;
      row.isEdit = false;
      // 清空inputAttrValue中存储的值
      inputAttrValue.value = "";
    }
  }
}

//事件6:检测要添加的属性名称是否存在
function enterAttrNameHandler() {
  if (formData.value) {
    // 过滤掉当前这条数据
    const filterAttrs = attrs.value.filter(
      (item) => item.id != formData.value?.id
    );

    // 在已经过滤掉的数据中去查找是否还有重复的
    const isExists = filterAttrs.find(
      (item) => item.attrName == formData.value?.attrName
    );
    // console.log(isExists);
    if (isExists) {
      ElMessage.error("已经存在同名属性了");
      formData.value.attrName = "";
    }
  }
}

/**
 * 提交保存
 */
async function saveAttrHandler() {
  if (formData.value) {
    const messageType = formData.value.id ? "修改" : "添加";
    try {
      await reqSaveAttrInfo(formData.value);
      ElMessage.success(`${messageType}成功`);
      attrListOrAdd.value = true;
      getAttrs();
    } catch (e) {
      ElMessage.error(`${messageType}失败`);
    }
  }
}
/**
 * 删除attr
 */
async function confirmDeleteAttrHandler(id: number) {
  console.log(id);
  try {
    await reqDeleteAttr(`${id}`);
    ElMessage.success("删除成功");
    getAttrs()
  } catch (e) {
    ElMessage.error('删除失败')
  }
}
</script>

<style lang="less" scoped></style>
